#include "widget.h"

#include "./ui_widget.h"

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
    ui->setupUi(this);

    // 创建标准项模型替代文件系统模型
    fileModel = new QStandardItemModel(this);
    
    // 创建表头项并设置居中对齐
    QStandardItem* nameHeader = new QStandardItem("文件名");
    QStandardItem* sizeHeader = new QStandardItem("大小");
    QStandardItem* timeHeader = new QStandardItem("修改时间");
    
    nameHeader->setTextAlignment(Qt::AlignCenter);
    sizeHeader->setTextAlignment(Qt::AlignCenter);
    timeHeader->setTextAlignment(Qt::AlignCenter);
    
    // 设置表头
    fileModel->setHorizontalHeaderItem(0, nameHeader);
    fileModel->setHorizontalHeaderItem(1, sizeHeader);
    fileModel->setHorizontalHeaderItem(2, timeHeader);

    // 设置TreeView
    treeView = new QTreeView(this);
    treeView->setModel(fileModel);

    // 设置字体大小
    QFont font = treeView->font();
    font.setPointSize(font.pointSize() * 2);  // 字体大小翻倍
    treeView->setFont(font);

    // 设置图标大小
    treeView->setIconSize(QSize(32, 32));  // 默认通常是16x16，这里设置为32x32

    // 设置行高以适应更大的字体和图标
    treeView->setStyleSheet("QTreeView::item { padding: 5px; }");

    // 创建按钮
    QPushButton *refreshButton = new QPushButton("刷新", this);
    QPushButton *downloadButton = new QPushButton("下载文件", this);
    refreshButton->setFixedSize(100, 50);
    downloadButton->setFixedSize(100, 50);
    connect(refreshButton, &QPushButton::clicked, this, &Widget::onRefreshButtonClicked);
    connect(downloadButton, &QPushButton::clicked, this, &Widget::onDownloadButtonClicked);

    // 创建水平布局放置按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(refreshButton);
    buttonLayout->addWidget(downloadButton);
    buttonLayout->addStretch();

    // 创建垂直布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(treeView);
    mainLayout->addLayout(buttonLayout);  // 添加按钮布局

    // 设置布局的边距
    mainLayout->setContentsMargins(10, 10, 10, 10);

    // 设置列宽比例
    treeView->header()->setSectionResizeMode(0, QHeaderView::Stretch);  // 文件名列自适应
    treeView->header()->setSectionResizeMode(1, QHeaderView::Fixed);    // 大小列固定宽度
    treeView->header()->setSectionResizeMode(2, QHeaderView::Fixed);    // 时间列固定宽度

    // 设置固定列的宽度
    treeView->setColumnWidth(1, 150);  // 大小列宽度
    treeView->setColumnWidth(2, 200);  // 时间列宽度

    // 设置窗口最小尺寸
    setMinimumSize(800, 600);

    // 设置网络管理器
    manager = new QNetworkAccessManager(this);
    connect(manager, &QNetworkAccessManager::finished, this, &Widget::onNetworkReply);

    // 初始化当前路径
    currentPath = "/";
    // 连接双击信号
    connect(treeView, &QTreeView::doubleClicked, this, &Widget::onTreeViewDoubleClicked);
    // 设置初始状态
    sendRequest(currentPath);
}

Widget::~Widget() { delete ui; }


void Widget::onTreeViewDoubleClicked(const QModelIndex &index) {
    qDebug() << "双击事件触发";

    // 获取双击的项
    QStandardItem *item = fileModel->itemFromIndex(index);
    if (!item) {
        qDebug() << "无法获取item";
        return;
    }

    qDebug() << "双击的项目:" << item->text();

    // 使用存储的文件夹信息来判断
    bool isFolder = item->data(Qt::UserRole).toBool();
    qDebug() << "是否是文件夹:" << isFolder;

    if (isFolder) {
        // 获取文件夹名称
        QString folderName = item->text();

        // 更新当前路径
        if (folderName == "..") {
            // 返回上级目录
            int lastSlash = currentPath.lastIndexOf('/', -2);  // -2是为了跳过末尾的斜杠
            if (lastSlash >= 0) {
                currentPath = currentPath.left(lastSlash + 1);
            }
        } else {
            // 进入子目录
            currentPath += folderName + "/";
        }

        // 发送新的网络请求
        sendRequest(currentPath);

        qDebug() << "正在请求新路径:" << currentPath;
    } else {
        qDebug() << "不是文件夹，忽略双击";
    }
}

void Widget::onNetworkReply(QNetworkReply *reply) {
    // 检查是否是文件列表请求
    QString requestPath = reply->url().path();
    if (requestPath.endsWith("/")) {  // 如果URL以/结尾，说明是请求文件列表
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray data = reply->readAll();
            QString html = QString::fromUtf8(data);

            // 调试输出
            qDebug() << "开始解析HTML...";

            // 清空现有数据
            fileModel->removeRows(0, fileModel->rowCount());

            // 修改正则表达式以匹配实际的HTML结构
            QRegExp rx("<tr><td><img src='([^']+)'[^>]*></td><td><a href='([^']+)'>([^<]+)</a></td><td>([^<]+)</td><td>([^<]*)</td></tr>");
            rx.setMinimal(false);

            int pos = 0;
            while ((pos = rx.indexIn(html, pos)) != -1) {
                QString iconPath = rx.cap(1);
                QString href = rx.cap(2);
                QString name = rx.cap(3);
                QString modTime = rx.cap(4);
                QString size = rx.cap(5);

                // 调试输出
                qDebug() << "找到匹配:";
                qDebug() << "  图标:" << iconPath;
                qDebug() << "  链接:" << href;
                qDebug() << "  名称:" << name;
                qDebug() << "  时间:" << modTime;
                qDebug() << "  大小:" << size;

                QList<QStandardItem *> row;
                QStandardItem *nameItem = new QStandardItem(name);
                QStandardItem *sizeItem = new QStandardItem(size);
                QStandardItem *timeItem = new QStandardItem(modTime);

                // 设置大小和时间列居中对齐
                sizeItem->setTextAlignment(Qt::AlignCenter);
                timeItem->setTextAlignment(Qt::AlignCenter);

                // 设置图标并存储是否为文件夹的信息
                bool isFolder = iconPath.contains("folder");
                if (isFolder) {
                    nameItem->setIcon(style()->standardIcon(QStyle::SP_DirIcon));
                    // 使用setData存储是否为文件夹的信息
                    nameItem->setData(true, Qt::UserRole);
                } else {
                    nameItem->setIcon(style()->standardIcon(QStyle::SP_FileIcon));
                    nameItem->setData(false, Qt::UserRole);
                }

                row.append(nameItem);
                row.append(sizeItem);
                row.append(timeItem);
                fileModel->appendRow(row);

                pos += rx.matchedLength();
            }

            qDebug() << "解析完成，找到" << fileModel->rowCount() << "个项目";

            if (fileModel->rowCount() == 0) {
                QMessageBox::warning(this, "提示", "未找到文件列表");
            }

            // 为返回上级目录的项也设置文件夹标志
            if (currentPath != "/") {
                QList<QStandardItem *> row;
                QStandardItem *nameItem = new QStandardItem("..");
                nameItem->setIcon(style()->standardIcon(QStyle::SP_DirIcon));
                nameItem->setData(true, Qt::UserRole);  // 标记为文件夹

                QStandardItem *sizeItem = new QStandardItem("");
                QStandardItem *timeItem = new QStandardItem("");

                sizeItem->setTextAlignment(Qt::AlignCenter);
                timeItem->setTextAlignment(Qt::AlignCenter);

                row.append(nameItem);
                row.append(sizeItem);
                row.append(timeItem);

                fileModel->insertRow(0, row);
            }
        } else {
            qDebug() << "Network Error:" << reply->error();
            qDebug() << "Error String:" << reply->errorString();
            qDebug() << "HTTP Status Code:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
            qDebug() << "Response Headers:" << reply->rawHeaderPairs();

            QMessageBox::warning(this, "错误",
                                 QString("获取文件列表失败:\nError: %1\nStatus: %2")
                                     .arg(reply->errorString())
                                     .arg(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()));
        }
    } else {
        qDebug() << "不是文件列表请求，忽略";
    }
    reply->deleteLater();
}

// 添加辅助函数来发送网络请求
void Widget::sendRequest(const QString &path) {
    QUrl url(QString("http://8.141.90.29%1").arg(path));
    QNetworkRequest request(url);

    // 添加认证信息
    QString credentials = QString("%1:%2").arg("user").arg("xin123456036");
    QByteArray auth = "Basic " + credentials.toUtf8().toBase64();
    request.setRawHeader("Authorization", auth);

    // 发送请求
    manager->get(request);
}

void Widget::onDownloadButtonClicked() {
    QModelIndex currentIndex = treeView->currentIndex();
    if (!currentIndex.isValid()) {
        QMessageBox::warning(this, "提示", "请先选择一个文件");
        return;
    }

    QStandardItem *item = fileModel->itemFromIndex(currentIndex);
    if (!item)
        return;

    // 检查是否是文件夹
    bool isFolder = item->data(Qt::UserRole).toBool();
    if (isFolder) {
        QMessageBox::warning(this, "提示", "不能下载文件夹");
        return;
    }

    // 获取文件名
    QString fileName = item->text();
    QString filePath = currentPath + fileName;

    // 创建下载请求
    QUrl url(QString("http://8.141.90.29%1").arg(filePath));
    QNetworkRequest request(url);

    // 添加认证信息
    QString credentials = QString("%1:%2").arg("user").arg("xin123456036");
    QByteArray auth = "Basic " + credentials.toUtf8().toBase64();
    request.setRawHeader("Authorization", auth);

    // 开始下载
    QNetworkReply *reply = manager->get(request);

    // 显示进度对话框
    QProgressDialog *progressDialog = new QProgressDialog("下载中...", "取消", 0, 0, this);
    progressDialog->setWindowModality(Qt::WindowModal);
    progressDialog->setMinimumDuration(0);
    progressDialog->show();

    // 连接信号
    connect(reply, &QNetworkReply::downloadProgress, [progressDialog](qint64 bytesReceived, qint64 bytesTotal) {
        if (bytesTotal > 0) {
            progressDialog->setMaximum(100);
            progressDialog->setValue((bytesReceived * 100) / bytesTotal);
        }
    });

    connect(progressDialog, &QProgressDialog::canceled, reply, &QNetworkReply::abort);

    connect(reply, &QNetworkReply::finished, this, [this, reply, progressDialog, fileName]() {
        progressDialog->close();
        progressDialog->deleteLater();

        if (reply->error() == QNetworkReply::NoError) {
            // 保存文件
            QFile file(fileName);
            if (file.open(QIODevice::WriteOnly)) {
                file.write(reply->readAll());
                file.close();
                QMessageBox::information(this, "成功", QString("文件 %1 下载完成").arg(fileName));
            } else {
                QMessageBox::warning(this, "错误", QString("无法保存文件: %1").arg(file.errorString()));
            }
        } else {
            QMessageBox::warning(this, "错误", QString("下载失败: %1").arg(reply->errorString()));
        }

        reply->deleteLater();
    });

    qDebug() << "开始下载文件:" << url.toString();
}

// 添加新的刷新按钮槽函数
void Widget::onRefreshButtonClicked() {
    // 重置当前路径到根目录
    currentPath = "/";
    // 发送请求获取根目录文件列表
    sendRequest(currentPath);
}
